﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using TeachingEval.Sys.DALFactory;
using TeachingEval.Sys.IDAL;

namespace TeachingEval.Sys.BLL
{
    /// <summary>
    /// 父类要逼迫子类给父类的一个属性赋值。
    /// 赋值的操作必须在父类的方法调用之前先执行。
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class BaseService<T> where T : class, new()
    {
        public IBaseDal<T> CurrentDal { get; set; }

        public IDbSession dbsession
        {
            get
            {
                return DbSessionFactory.GetCurrentDbSession();
            }
        }

        public BaseService()//基类的构造函数
        {
            SetCurrentDal();//抽象方法。
        }

        public abstract void SetCurrentDal();//抽象方法：要求子类必须实现。



        #region 查询crud
        public IQueryable<T> GetEntities(Expression<Func<T, bool>> whereLambda)
        {
            return CurrentDal.GetEntities(whereLambda);
        }
        //分页查询
        public IQueryable<T> GetPageEntities<S>(int pageSize, int pageIndex, out int total,
                                                Expression<Func<T, bool>> whereLambda,
                                                Expression<Func<T, S>> orderByLambda,
                                                bool isAsc
           )
        {
            return CurrentDal.GetPageEntities(pageSize, pageIndex, out total, whereLambda, orderByLambda, isAsc);
        }
        #endregion

        #region cud

        public T Add(T entity)
        {
            CurrentDal.Add(entity);
            dbsession.SaveChanges();
            return entity;
        }

        public bool Update(T entity)
        {
            CurrentDal.Update(entity);
            return dbsession.SaveChanges();
        }

        public bool Delete(T entity)
        {
            CurrentDal.Delete(entity);
            return dbsession.SaveChanges();
        }
        #endregion

    }
}
